package com.obggtc.picture.security;

import com.alibaba.fastjson.JSON;
import com.obggtc.picture.common.R;
import com.obggtc.picture.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;

    public JwtAuthenticationFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 检查是否是匿名访问的接口
        String requestURI = request.getRequestURI();
        if (isAnonymousPath(requestURI)) {
            // 对于匿名接口，直接放行，不进行JWT验证
            filterChain.doFilter(request, response);
            return;
        }
        
        try {
            // 获取请求头中的Authorization
            String authHeader = request.getHeader("Authorization");
            
            if (StringUtils.hasText(authHeader) && authHeader.startsWith("Bearer ")) {
                // 提取Token
                String token = authHeader.substring(7);
                
                // 验证Token
                if (jwtUtils.validateToken(token) && !jwtUtils.isTokenExpired(token)) {
                    // 从Token中获取用户名
                    String username = jwtUtils.getUsernameFromToken(token);
                    
                    // 创建认证信息
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username, null, null);
                    
                    // 设置认证信息到Security上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                } else {
                    // Token无效或过期，直接返回错误响应
                    handleAuthenticationError(response, "Token无效或已过期，请重新登录");
                    return;
                }
            }
            // 如果没有Token，不抛出异常，让后续的权限检查处理
        } catch (Exception e) {
            // 清除认证上下文
            SecurityContextHolder.clearContext();
            // 直接返回错误响应
            handleAuthenticationError(response, "Token验证失败: " + e.getMessage());
            return;
        }
        
        filterChain.doFilter(request, response);
    }

    /**
     * 检查是否是匿名访问的路径
     */
    private boolean isAnonymousPath(String requestURI) {
        // 匿名访问的路径列表
        String[] anonymousPaths = {"/auth/login", "/static/"};
        
        for (String path : anonymousPaths) {
            if (requestURI.startsWith(path)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 处理认证错误，直接返回JSON响应
     */
    private void handleAuthenticationError(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        
        R<String> errorResponse = R.authFailed(message);
        response.getWriter().write(JSON.toJSONString(errorResponse));
    }
} 